package cn.com.shadowless.basepopview.base;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.viewbinding.ViewBinding;

import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.core.CenterPopupView;

import java.lang.reflect.InvocationTargetException;

import cn.com.shadowless.basepopview.R;
import cn.com.shadowless.basepopview.event.PopPublicEvent;


/**
 * 居中弹窗基类
 *
 * @param <VB> ViewBinding类型参数
 * @author sHadowLess
 */
public abstract class BaseCenterPopView<VB extends ViewBinding> extends CenterPopupView implements
        PopPublicEvent.InitViewBinding<VB>, PopPublicEvent.InitViewClick, PopPublicEvent.InitEvent {

    /**
     * ViewBinding绑定视图对象
     */
    private VB bind = null;

    /**
     * 是否已初始化标识
     */
    private boolean isInit = false;

    /**
     * 构造函数
     *
     * @param context 上下文对象
     */
    public BaseCenterPopView(@NonNull Context context) {
        super(context);
    }

    /**
     * 获取实现布局ID
     *
     * @return 布局资源ID
     */
    @Override
    protected int getImplLayoutId() {
        return getContext().getResources().getIdentifier(
                this.getLayoutNameByBindingClass(initViewBindingGenericsClass(this)),
                DEF_TYPE,
                getContext().getPackageName()
        );
    }

    /**
     * 弹窗创建时的回调方法
     */
    @Override
    protected void onCreate() {
        super.onCreate();
        try {
            bind = inflateView(this, getPopupImplView());
        } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
            throw new RuntimeException("视图无法反射初始化，若动态布局请检查setBindViewClass是否传入或重写inflateView手动实现ViewBinding创建" + Log.getStackTraceString(e));
        }
        if (isDefaultBackground()) {
            getPopupImplView().setBackground(AppCompatResources.getDrawable(getContext(), R.drawable.bg_base_pop_radius_shape));
        }
        initObject();
        initView();
        initViewListener();
        initDataListener();
        initData();
        isInit = true;
    }

    /**
     * 显示弹窗
     *
     * @return BasePopupView实例
     */
    @Override
    public BasePopupView show() {
        if (isInit) {
            updateData();
        }
        return super.show();
    }

    /**
     * 获取绑定视图控件
     *
     * @return ViewBinding实例
     */
    protected VB getBindView() {
        return bind;
    }
}